package com.fyl.utils;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class PageQuery implements Serializable {

    private static final long serialVersionUID = 6113277744104239499L;

    private Integer current = 1;// 页数
    private Integer size = 10;// 每页条数
    private String sort;

    public static <T> Page<T> buildPage(PageQuery pageQuery) {
        Page<T> page = new Page<>();
        page.setCurrent(pageQuery.getCurrent());
        page.setSize(pageQuery.getSize());
        page.setOrders(pageQuery.getOrders());
        return page;
    }

    public Integer getCurrent() {
        return current;
    }

    public void setCurrent(Integer current) {
        this.current = current;
    }

    public Integer getSize() {
        return size;
    }

    public void setSize(Integer size) {
        this.size = size;
    }

    public String getSort() {
        return sort;
    }

    public void setSort(String sort) {
        this.sort = sort;
    }

    public List<OrderItem> getOrders() {
        if (StringUtils.isBlank(sort)) {
            return null;
        }
        String[] sorts = sort.split(";");
        List<OrderItem> orders = Arrays.stream(sorts).map(el -> {
            String[] split = el.split(",");
            // 判断列名称的合法性，防止SQL注入。只能是【字母，数字，下划线】
            if (!split[0].matches("[A-Za-z0-9_]+")) {
                return null;
            }
            String columnName = split[0].replaceAll("[A-Z]", "_$0").toLowerCase()/*.replaceAll("\\s*", "")*/;
            if (split.length == 2 && "DESC".equalsIgnoreCase(split[1])) {
                return OrderItem.desc(columnName);
            }
            return OrderItem.asc(columnName);
        }).filter(Objects::nonNull).collect(Collectors.toList());

        return orders;
    }

}
